package cn.view;


import cn.comon.CSVUtil;
import cn.comon.VerticalTextCellRenderer;
import cn.dao.EmployeeDao;
import cn.entity.Employee;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class EmployeeManageView extends JInternalFrame {
    JTable detail;
    DefaultTableModel model;
    JPanel Jbutton;

    public EmployeeManageView() {
        super("员工管理页面", false, true, false, true);
        initializeComponents();
        this.setSize(700, 500);
        this.setVisible(true);
    }

    private void initializeComponents() {
        // 设置布局管理器
        getContentPane().setLayout(new BorderLayout());
        // 初始化数据和按钮
        getDetailData();
        setButton();
    }

    private void getDetailData() {
        EmployeeDao dao = new EmployeeDao();
        List<Object[]> ls = dao.selectAll();
        String[] title = { "员工编号", "员工姓名", "员工密码", "级别", "员工电话", "员工工资", "备注" };
        model = new DefaultTableModel(ls.toArray(new Object[][]{}), title);
        detail = new JTable(model);
        detail.setDefaultEditor(Object.class, null);
        detail.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        // 设置表格列宽
        setColumnWidths(detail, new int[]{80, 90, 90,50, 90, 80, 140});
        // 设置表格行高
        detail.setRowHeight(15);
        // 设置自定义渲染器
        for (int i = 0; i < detail.getColumnCount(); i++) {
            detail.getColumnModel().getColumn(i).setCellRenderer(new VerticalTextCellRenderer());
        }

        JScrollPane scrollPane = new JScrollPane(detail, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        getContentPane().add(scrollPane, BorderLayout.CENTER);
    }

    private void setColumnWidths(JTable table, int[] widths) {
        for (int i = 0; i < widths.length; i++) {
            table.getColumnModel().getColumn(i).setPreferredWidth(widths[i]);
        }
    }

    public void refreshEmployeeData(){
        EmployeeDao dao = new EmployeeDao();
        List<Object[]> ls = dao.selectAll();
        model.setRowCount(0);
        for (Object[] row : ls) {
            model.addRow(row);
        }
    }


    private JPanel createEmployeeFormPanel(JTextField[] fields) {
        for(int i = 0; i < fields.length; i++)
            fields[i] = new JTextField(10);

        JPanel panel = new JPanel(new GridLayout(7, 2));
        panel.add(new JLabel("员工编号:"));
        panel.add(fields[0]);
        panel.add(new JLabel("员工姓名:"));
        panel.add(fields[1]);
        panel.add(new JLabel("员工密码:"));
        panel.add(fields[2]);
        panel.add(new JLabel("级别:"));
        panel.add(fields[3]);
        panel.add(new JLabel("员工电话:"));
        panel.add(fields[4]);
        panel.add(new JLabel("员工工资:"));
        panel.add(fields[5]);
        panel.add(new JLabel("备注:"));
        panel.add(fields[6]);

        return panel;
    }

    private Employee getEmployeeFromFields(JTextField[] fields) {
        Employee emp = new Employee();
        emp.setEid(fields[0].getText());
        emp.setEname(fields[1].getText());
        emp.setEpw(fields[2].getText());
        emp.setElevel(fields[3].getText());
        emp.setEPhone(fields[4].getText());
        emp.setSalary(fields[5].getText());
        emp.setNotes(fields[6].getText());
        return emp;
    }

    private List<Employee> convertToEmployeeList(List<Object[]> data) {
        List<Employee> employees = new ArrayList<>();
        for (Object[] row : data) {
            Employee emp = new Employee();
            emp.setEid((String) row[0]);
            emp.setEname((String) row[1]);
            emp.setEpw((String) row[2]);
            emp.setElevel((String) row[3]);
            emp.setEPhone((String) row[4]);
            emp.setSalary((String) row[5]);
            emp.setNotes((String) row[6]);
            employees.add(emp);
        }
        return employees;
    }

    private void showAddEmployeeDialog() {
        JTextField[] fields = new JTextField[7];
        JPanel panel = createEmployeeFormPanel(fields);

        int result = JOptionPane.showConfirmDialog(null, panel, "添加员工", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            Employee emp = getEmployeeFromFields(fields);
            if (emp.getEid().isEmpty()) {
                emp.setEid(null); // 设置为null以便触发器生成新的Eid
            }

            EmployeeDao dao = new EmployeeDao();
            List<Employee> empList = new ArrayList<>();
            empList.add(emp);
            try {
                dao.addEmp(empList);
                // 更新表格视图
                model.addRow(new Object[]{
                        emp.getEid(),
                        emp.getEname(),
                        emp.getEpw(),
                        emp.getElevel(),
                        emp.getEPhone(),
                        emp.getSalary(),
                        emp.getNotes()
                });
                refreshEmployeeData();
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(null, "添加员工失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }


    private void showEditEmployeeDialog(int selectedRow) {
        JTextField[] fields = new JTextField[7];
        JPanel panel = createEmployeeFormPanel(fields);
        // 填充现有数据
        fields[0].setText((String) model.getValueAt(selectedRow, 0));
        fields[1].setText((String) model.getValueAt(selectedRow, 1));
        fields[2].setText((String) model.getValueAt(selectedRow, 2));
        fields[3].setText((String) model.getValueAt(selectedRow, 3));
        fields[4].setText((String) model.getValueAt(selectedRow, 4));
        fields[5].setText((String) model.getValueAt(selectedRow, 5));
        fields[6].setText((String) model.getValueAt(selectedRow, 6));

        int result = JOptionPane.showConfirmDialog(null, panel, "修改员工", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            String originalEid = (String) model.getValueAt(selectedRow, 0);
            Employee emp = getEmployeeFromFields(fields);

            EmployeeDao dao = new EmployeeDao();
            try {
                dao.updateEmp(emp, originalEid);
                // 更新表格视图
                model.setValueAt(emp.getEid(), selectedRow, 0);
                model.setValueAt(emp.getEname(), selectedRow, 1);
                model.setValueAt(emp.getEpw(), selectedRow, 2);
                model.setValueAt(emp.getElevel(), selectedRow, 3);
                model.setValueAt(emp.getEPhone(), selectedRow, 4);
                model.setValueAt(emp.getSalary(), selectedRow, 5);
                model.setValueAt(emp.getNotes(), selectedRow, 6);
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(null, "更新员工失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }


    private void showQueryEmployeeDialog() {
        JTextField[] fields = new JTextField[7];
        JPanel panel = createEmployeeFormPanel(fields);

        int result = JOptionPane.showConfirmDialog(null, panel, "查询员工", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            Employee criteria = getEmployeeFromFields(fields);

            EmployeeDao dao = new EmployeeDao();
            List<Employee> employees = dao.queryEmployees(criteria);

            if (employees.isEmpty()) {
                JOptionPane.showMessageDialog(null, "没有符合员工信息");
            } else {
                // 清空现有表格数据
                model.setRowCount(0);
                // 添加查询结果到表格
                for (Employee emp : employees) {
                    model.addRow(new Object[]{
                            emp.getEid(),
                            emp.getEname(),
                            emp.getEpw(),
                            emp.getElevel(),
                            emp.getEPhone(),
                            emp.getSalary(),
                            emp.getNotes()
                    });
                }
            }
        }
    }

    private void showExportEmployeeDialog() {
        String[] options = {"导出所有员工数据", "导出筛选后的员工数据", "导出除筛选外的员工数据"};
        int choice = JOptionPane.showOptionDialog(
                null,
                "请选择导出选项",
                "导出员工数据",
                JOptionPane.DEFAULT_OPTION,
                JOptionPane.INFORMATION_MESSAGE,
                null,
                options,
                options[0]
        );

        // 如果用户选择关闭对话框或点击取消按钮，直接返回
        if (choice == JOptionPane.CLOSED_OPTION) {
            return;
        }

        List<Employee> employeesToExport = new ArrayList<>();

        if (choice == 0) { // 导出所有员工数据
            EmployeeDao dao = new EmployeeDao();
            List<Object[]> allEmployeesData = dao.selectAll();
            employeesToExport = convertToEmployeeList(allEmployeesData);
        } else {
            JTextField[] fields = new JTextField[7];
            JPanel panel = createEmployeeFormPanel(fields);

            int result = JOptionPane.showConfirmDialog(null, panel, "筛选员工", JOptionPane.OK_CANCEL_OPTION);
            // 如果用户选择关闭对话框或点击取消按钮，直接返回
            if (result == JOptionPane.CLOSED_OPTION || result == JOptionPane.CANCEL_OPTION) {
                return;
            }

            Employee criteria = getEmployeeFromFields(fields);
            EmployeeDao dao = new EmployeeDao();
            List<Employee> filteredEmployees = dao.queryEmployees(criteria);

            if (choice == 1) { // 导出筛选后的员工数据
                employeesToExport = filteredEmployees;
            } else if (choice == 2) { // 导出除筛选外的员工数据
                List<Object[]> allEmployeesData = dao.selectAll();
                List<Employee> allEmployees = convertToEmployeeList(allEmployeesData);
                allEmployees.removeAll(filteredEmployees);
                employeesToExport = allEmployees;
            }
        }

        if (!employeesToExport.isEmpty()) {
            exportEmployeesToCSV(employeesToExport);
        } else {
            JOptionPane.showMessageDialog(null, "没有符合条件的员工数据可导出");
        }
    }


    private void exportEmployeesToCSV(List<Employee> employees) {
        String[] headers = {"员工编号", "员工姓名", "员工密码", "级别", "员工电话", "员工工资", "备注"};
        List<Object[]> data = new ArrayList<>();

        for (Employee emp : employees) {
            data.add(new Object[]{
                    emp.getEid(),
                    emp.getEname(),
                    emp.getEpw(),
                    emp.getElevel(),
                    emp.getEPhone(),
                    emp.getSalary(),
                    emp.getNotes()
            });
        }

        File csvFile = CSVUtil.createCSVFile(headers, data, "output/path", "员工数据");
        if (csvFile != null) {
            JOptionPane.showMessageDialog(null, "员工数据已成功导出到: " + csvFile.getAbsolutePath());
        } else {
            JOptionPane.showMessageDialog(null, "导出员工数据失败");
        }
    }


    private void setButton() {
        Jbutton = new JPanel();
        Jbutton.setLayout(new FlowLayout());

        JButton addButton = new JButton("添加员工");
        addButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                showAddEmployeeDialog();
            }
        });


        JButton editButton = new JButton("修改员工");
        editButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                int selectedRow = detail.getSelectedRow();
                if (selectedRow != -1) {
                    showEditEmployeeDialog(selectedRow);
                } else {
                    JOptionPane.showMessageDialog(null, "请选择要修改的员工");
                }
            }
        });



        JButton delButton = new JButton("删除员工");
        delButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                int selectedRow = detail.getSelectedRow();
                if (selectedRow != -1) {
                    String eid = (String) model.getValueAt(selectedRow, 0);
                    EmployeeDao dao = new EmployeeDao();
                    dao.deleteEmp(eid);
                    model.removeRow(selectedRow);
                } else {
                    JOptionPane.showMessageDialog(null, "请选择要删除的员工");
                }
            }
        });

        JButton queryButton = new JButton("查询员工");
        queryButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                showQueryEmployeeDialog();
            }
        });

        JButton exportButton = new JButton("导出员工数据");
        exportButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                showExportEmployeeDialog();
            }
        });

        Jbutton.add(addButton);
        Jbutton.add(editButton);
        Jbutton.add(delButton);
        Jbutton.add(queryButton);
        Jbutton.add(exportButton);

        getContentPane().add(Jbutton, BorderLayout.SOUTH);

    }
}
